package org.sraosha.framework.manager;

import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@Slf4j
public class EMailManager {

    private String sendAccount;

    private String sendPassword;

    private String eMailSMTPHost;

    private Session session;

    public EMailManager(String sendAccount, String sendPassword, String eMailSMTPHost) {
        this.sendAccount = sendAccount;
        this.sendPassword = sendPassword;
        this.eMailSMTPHost = eMailSMTPHost;

        // 1.创建参数配置，用于连接邮件服务器的参数配置
        Properties props = new Properties();
        // 使用的协议（JavaMail规范要求）
        props.setProperty("mail.transport.protocol", "smtp");
        // 发件人的邮箱的SMTP服务器地址
        props.setProperty("mail.smtp.host", this.eMailSMTPHost);
        // 需要请求认证
        props.setProperty("mail.smtp.auth", "true");

        // 2.根据配置创建会话对象, 用于和邮件服务器交互
        this.session = Session.getInstance(props);
    }

    /**
     * 发送邮件
     * @param receiveAccount
     * @param receiveRealName
     * @param subject
     * @param content
     */
    public void send(String receiveAccount, String receiveRealName, String subject, String content) {
        // 1.创建一封邮件
        MimeMessage mimeMessage = new MimeMessage(session);
        try {
            // 2.From:发件人
            mimeMessage.setFrom(new InternetAddress(this.sendAccount, this.sendAccount, "UTF-8"));
            // 3.To:收件人（可以增加多个收件人、抄送、密送）
            mimeMessage.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveAccount, receiveRealName, "UTF-8"));
            // 4.Subject: 邮件主题
            mimeMessage.setSubject(subject, "UTF-8");
            // 5.Content: 邮件正文（可以使用html标签）（内容有广告嫌疑，避免被邮件服务器误认为是滥发广告以至返回失败，请修改发送内容）
            mimeMessage.setContent(content, "text/html;charset=UTF-8");
            // 6.设置发件时间
            mimeMessage.setSentDate(new Date());
            // 7.保存设置
            mimeMessage.saveChanges();
            // 8.根据 Session获取邮件传输对象
            Transport transport = session.getTransport();
            // 9.使用邮箱账号和密码连接邮件服务器, 这里认证的邮箱必须与 message中的发件人邮箱一致,否则报错
            transport.connect(this.sendAccount, this.sendPassword);
            // 10.发送邮件,发到所有的收件地址,message.getAllRecipients()获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            log.debug("邮件发送成功");
            // 11.关闭连接
            transport.close();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
